package com.test.fundible.fundible_07_loan_status;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.fundible.R;
import com.test.fundible.fundible_04_home.MainAct_fundibleivity;
import com.test.fundible.fundible_01_launcher.App_fundibleShow_fundibleCustomize;
import com.test.fundible.fundible_01_launcher.Recommend_fundibleAppInfo;
import com.test.fundible.fundible_05_process.Pro_fundiblecessIn_fundiblefo;
import com.test.fundible.fundible_05_process.Acc_fundibleountLi_fundiblest_Fr;
import com.test.fundible.fundible_05_process.Ba_fundiblenkAcc_fundibleount_Fr;
import com.test.fundible.fundible_06_loan_apply.LoanApplyDetail;
import com.test.fundible.Othe_fundiblersInfo;
import com.test.fundible.fundible_05_process.Bin_fundibledAcco_fundibleuntChannelDialog_Fr;
import com.test.fundible.fundible_05_process.Bin_fundibledAccount_fundibleDialog_Fr;
import com.test.fundible.fundible_05_process.Delete_fundibleAccountDi_fundiblealog_Fr;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.FundibleUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LoanSta_fundibleteWaitFra_fundiblegment extends Base_fundibleLnFragment {

    private SwipeRefreshLayout refreshLayout;
    private View loanStatusBgView;
    private ImageView loanStatusIv;
    private TextView loanStatusTv;
    private ImageButton refreshStatusIb;
    private TextView loanAmountTv;
    private TextView loanTermTv;
    private View tipsView;
    private TextView tipsTitleTv;
    private TextView tipsTv;
    private TextView accountTitleTv;
    private LinearLayout accountGroupLayout;
    private View addAccountBtn;
    private View recommendView;
    private LinearLayout recommendGroupLayout;

    private String bindChannelMobile_fundible = "";

    private static String TAG = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_loan_fundiblestate_wait, container, false);

        refreshLayout = view.findViewById(R.id.flfw_refresh_layout);
        loanStatusBgView = view.findViewById(R.id.flfw_view_loan_status);
        loanStatusIv = view.findViewById(R.id.flfw_iv_loan_status);
        loanStatusTv = view.findViewById(R.id.flfw_tv_loan_status);
        refreshStatusIb = view.findViewById(R.id.flfw_ib_refresh_status);
        loanAmountTv = view.findViewById(R.id.flfw_tv_loan_amount);
        loanTermTv = view.findViewById(R.id.flfw_tv_loan_term);
        tipsView = view.findViewById(R.id.flfw_view_tips);
        tipsTitleTv = view.findViewById(R.id.flfw_tv_tips_title);
        tipsTv = view.findViewById(R.id.flfw_tv_tips);
        accountTitleTv = view.findViewById(R.id.flfw_tv_account_title);
        accountGroupLayout = view.findViewById(R.id.flfw_layout_account_group);
        addAccountBtn = view.findViewById(R.id.flfw_btn_add_account);
        recommendView = view.findViewById(R.id.flfw_view_recommend);
        recommendGroupLayout = view.findViewById(R.id.flfw_layout_recommend_group);

        //两个刷新控件
        refreshStatusIb.setOnClickListener(v -> {

            startLoading(requireContext(),"");

            OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"REFRESH_CLICK","");

            OkHttpUtil.getInstance_fundible().requestUsPrcs(() -> {
                String state = Pro_fundiblecessIn_fundiblefo.getInstance_fundible().getFundibleUtil();
                if (FundibleUtil.isStateChange_fundible(state)) {//刷新用户状态
                    stopLoading();
                    FragmentActivity activity = requireActivity();
                    FundibleUtil.clearState_fundible();
                    activity.startActivity(new Intent(activity, MainAct_fundibleivity.class));
                    activity.finish();
                }else {
                    OkHttpUtil.getInstance_fundible().fetchLnAplDetail(() -> OkHttpUtil.getInstance_fundible().fetchLauncherConfig(this::refresh_fundible));
                }
            });

        });

        refreshLayout.setOnRefreshListener(() -> {

            refreshLayout.setRefreshing(false);

            startLoading(requireContext(),"");

            OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"REFRESH_PULL","");

            OkHttpUtil.getInstance_fundible().requestUsPrcs(() -> {
                String state = Pro_fundiblecessIn_fundiblefo.getInstance_fundible().getFundibleUtil();
                if (FundibleUtil.isStateChange_fundible(state)) {//刷新用户状态
                    stopLoading();
                    FragmentActivity activity = requireActivity();
                    FundibleUtil.clearState_fundible();
                    activity.startActivity(new Intent(activity, MainAct_fundibleivity.class));
                    activity.finish();
                }else {
                    OkHttpUtil.getInstance_fundible().fetchLnAplDetail(() -> OkHttpUtil.getInstance_fundible().fetchLauncherConfig(this::refresh_fundible));
                }
            });

        });

        init_fundible();

        return view;
    }

    private void init_fundible(){
        //状态：审核通过放款中
        if (Pro_fundiblecessIn_fundiblefo.getInstance_fundible().isOrderLoaning_fundible()){
            TAG = "LOANING";
            loanStatusBgView.setBackgroundResource(R.drawable.bg_yellow_ll_rc12dp_border_yellow_2dp);
            loanStatusIv.setBackgroundResource(R.drawable.img_loan_status_loaning);
            loanStatusTv.setText(getString(R.string.loan_status_in_review));
            loanStatusTv.setTextColor(Color.parseColor("#FFFF8717"));
            refreshStatusIb.setVisibility(View.GONE);
        }

        //状态：审核中
        else {
            TAG = "REVIEW";
            loanStatusBgView.setBackgroundResource(R.drawable.bg_blue_ll_rc12dp_border_blue_2dp);
            loanStatusIv.setBackgroundResource(R.drawable.img_loan_status_review);
            loanStatusTv.setText(getString(R.string.loan_status_in_review));
            loanStatusTv.setTextColor(Color.parseColor("#FF5987FF"));
            refreshStatusIb.setVisibility(View.VISIBLE);
        }


        //法语区初始化
        if (FundibleUtil.isFrench_fundible()){
            accountTitleTv.setText(getString(R.string.loan_status_account_title_add_more));
            addAccountBtn.setVisibility(View.VISIBLE);
        }

        //非法语区初始化
        else {
            accountTitleTv.setText(getString(R.string.loan_status_account_title));
            addAccountBtn.setVisibility(View.GONE);
        }

        //提示文案初始化
        if (App_fundibleShow_fundibleCustomize.getInstance_fundible().isShowWaitTips()){
            tipsView.setVisibility(View.VISIBLE);
            String title = App_fundibleShow_fundibleCustomize.getInstance_fundible().getWaitTipsTitle();
            String content = App_fundibleShow_fundibleCustomize.getInstance_fundible().getWaitTipsText();
            if (!TextUtils.isEmpty(title)) tipsTitleTv.setText(title);
            tipsTv.setText(content);
        }else tipsView.setVisibility(View.GONE);

    }

    @Override
    public void onResume() {
        super.onResume();
        startLoading(requireContext(),"");
        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"START","");
        OkHttpUtil.getInstance_fundible().fetchLnAplDetail(() ->
                OkHttpUtil.getInstance_fundible().fetchLauncherConfig(this::refresh_fundible)
        );
    }

    //更新额度、日期、推荐app显示
    @SuppressLint("SetTextI18n")
    public void refresh_fundible(){

        String currency = LoanApplyDetail.getInstance_fundible().getCurrency_fundible();

        loanAmountTv.setText(LoanApplyDetail.getInstance_fundible().getAmount_fundible()+" "+currency);
        loanTermTv.setText(LoanApplyDetail.getInstance_fundible().getTermStr_fundible());

        //app推荐显示
        refreshRecommendAppList_fundible();

        //放款账户显示
        refreshAccounts_fundible();

    }

    //更新推荐App显示
    public void refreshRecommendAppList_fundible(){
        if (!App_fundibleShow_fundibleCustomize.getInstance_fundible().getRecommendFlag_fundible()) {
            recommendView.setVisibility(View.GONE);
            return;
        }
        recommendView.setVisibility(View.VISIBLE);
        recommendGroupLayout.removeAllViews();
        ArrayList<Recommend_fundibleAppInfo> recommendAppInfos = App_fundibleShow_fundibleCustomize.getInstance_fundible().getRecommendAppList_fundible();
        for (Recommend_fundibleAppInfo recommendAppInfo:recommendAppInfos){
            addRecommendApp_fundible(recommendAppInfo);
        }
    }

    //添加推荐App
    private void addRecommendApp_fundible(Recommend_fundibleAppInfo recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_fundible_recommend_app,null);

        ImageView appLogoIv = itemView.findViewById(R.id.iraa_iv_app_logo);
        TextView appNameTv = itemView.findViewById(R.id.iraa_tv_app_name);
        TextView appAmountTv = itemView.findViewById(R.id.iraa_tv_app_amount);
        TextView appRateTv = itemView.findViewById(R.id.iraa_tv_app_rate);
        TextView appDownloadTv = itemView.findViewById(R.id.iraa_tv_app_download);
        View installBtn = itemView.findViewById(R.id.iraa_btn_install);

        appNameTv.setText(recommendAppInfo.getAp_fundiblepName());
        appAmountTv.setText(recommendAppInfo.getAmou_fundiblentText());
        appRateTv.setText(recommendAppInfo.getSc_fundibleore());
        appDownloadTv.setText(recommendAppInfo.getDow_fundiblenloads());

        //Install按键
        installBtn.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"RECOMMEND_"+recommendAppInfo.getAp_fundiblepName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getP_fundibleath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });

        //加载logo
        if (recommendAppInfo.getLogo_fundibleBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getL_fundibleogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLo_fundiblegoB_fundibleitmap(bitmap);
                        FundibleUtil.safeRun(() -> appLogoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else appLogoIv.setImageBitmap(recommendAppInfo.getLogo_fundibleBitmap());

        recommendGroupLayout.addView(itemView);
    }

    //放款账户显示
    private void refreshAccounts_fundible(){

        accountGroupLayout.removeAllViews();

        if (FundibleUtil.isGhana_fundible()){//加纳

            stopLoading();

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_fundible_account_show,null);
            TextView accountTv = accountView.findViewById(R.id.iasa_tv_account);
            accountTv.setText(LoanApplyDetail.getInstance_fundible().getWltMobile_Gh_fundible());
            accountGroupLayout.addView(accountView);
            afterFinishInit_fundible();

        }else if (FundibleUtil.isFrench_fundible()){//法语区

            addAccountBtn.setOnClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"ADD_CLICK","");
                new Bin_fundibledAccount_fundibleDialog_Fr(requireActivity(), TAG,
                        mobile -> {
                            bindChannelMobile_fundible = mobile;
                            OkHttpUtil.getInstance_fundible().fetchWalletAccountList_fr(this::refreshAccountList_Fr_fundible);
                        }
                ).show();
            });

            OkHttpUtil.getInstance_fundible().fetchWalletAccountList_fr(this::refreshAccountList_Fr_fundible);

        }else {//其他国家

            stopLoading();

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_fundible_account_show,null);
            TextView accountTv = accountView.findViewById(R.id.iasa_tv_account);
            accountTv.setText(LoanApplyDetail.getInstance_fundible().getBkAccount_NiUgKe_fundible());
            accountGroupLayout.addView(accountView);
            afterFinishInit_fundible();

        }
    }

    //更新法语区绑卡列表
    public void refreshAccountList_Fr_fundible(){

        accountGroupLayout.removeAllViews();

        for (Ba_fundiblenkAcc_fundibleount_Fr account: Acc_fundibleountLi_fundiblest_Fr.getInstance_fundible().getBankAccountList_fundible()){
            addAccount_Fr_fundible(account);
        }

        //更新列表后，判断是否需要绑定运营商
        if (!TextUtils.isEmpty(bindChannelMobile_fundible) ){
            stopLoading();
            if (Othe_fundiblersInfo.getInstance_fundible().getAddBindFlag_fundible()){
                new Bin_fundibledAcco_fundibleuntChannelDialog_Fr(
                        requireContext(),
                        bindChannelMobile_fundible,
                        null,
                        () -> {
                            startLoading(requireContext(),"");
                            OkHttpUtil.getInstance_fundible().addWalletAccount_Fr(
                                    bindChannelMobile_fundible,
                                    bindChannelMobile_fundible,
                                    Othe_fundiblersInfo.getInstance_fundible().getChannel_fundible(),
                                    () -> OkHttpUtil.getInstance_fundible().fetchWalletAccountList_fr(this::refreshAccountList_Fr_fundible),
                                    false
                            );
                        }
                ).show();
                bindChannelMobile_fundible = "";
            }
        }else afterFinishInit_fundible();
    }

    //法语区添加放款卡
    private void addAccount_Fr_fundible(Ba_fundiblenkAcc_fundibleount_Fr account){
        if (account == null) return;

        String desc = account.getWalletDesc_fundible();

        View accountView = View.inflate(requireContext(), R.layout.item_fundible_account_fr, null);
        TextView titleTv = accountView.findViewById(R.id.iafa_tv_title);
        ImageView logoIv = accountView.findViewById(R.id.iafa_iv_logo);
        TextView channelTv = accountView.findViewById(R.id.iafa_tv_channel);
        TextView mobileTv = accountView.findViewById(R.id.iafa_tv_mobile);
        ImageButton deleteIb = accountView.findViewById(R.id.iafa_ib_delete_account);

        titleTv.setVisibility(View.GONE);
        mobileTv.setText(account.getWalletMobile_fundible());
        channelTv.setText(desc);

        //删除卡
        deleteIb.setOnClickListener(v -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"DELETE_CLICK",account.getWalletMobile_fundible());
            new Delete_fundibleAccountDi_fundiblealog_Fr(requireActivity(),account, TAG,
                    () -> OkHttpUtil.getInstance_fundible().fetchWalletAccountList_fr(this::refreshAccountList_Fr_fundible)).show();
        });

        accountGroupLayout.addView(accountView);

        //获取图标
        if (App_fundibleShow_fundibleCustomize.getInstance_fundible().getChannelLogoByDesc_fundible(desc) == null){
            new Thread(() -> {
                try {
                    if (TextUtils.isEmpty(account.getWalletLogo_fundible())) return;
                    if (!App_fundibleShow_fundibleCustomize.getInstance_fundible().hasAccountChannel_fundible()) return;
                    URL url = new URL(account.getWalletLogo_fundible());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        App_fundibleShow_fundibleCustomize.getInstance_fundible().setChannelLogoByDesc_fundible(desc,bitmap);
                        FundibleUtil.safeRun(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(App_fundibleShow_fundibleCustomize.getInstance_fundible().getChannelLogoByDesc_fundible(desc));

    }

    //页面显示初始化结束后获取评分弹窗配置
    private void afterFinishInit_fundible(){
        OkHttpUtil.getInstance_fundible().fetchRateConfig(this::onStarWindowConfigResponse_fundible);
    }

    //评分弹窗显示流程
    public void onStarWindowConfigResponse_fundible(){

        stopLoading();
        
        //1.活动弹窗
        if (RateAc_fundibletiveWind_fundibleowConfig.getInstance().isSwitch_fundible() &&
                FundibleUtil.getActivedialogCount_fundible()< RateAc_fundibletiveWind_fundibleowConfig.getInstance().getNum_fundible()){
            new Rate_fundibleActive_fundibleDialog((AppCompatActivity) requireActivity()).show();
            return;
        }

        //2.评价弹窗
        if (Rate_fundibleNormalW_fundibleindowConfig.getInstance().isSwitch_fundible() &&
                FundibleUtil.getNormaldialogCount_fundible()< Rate_fundibleNormalW_fundibleindowConfig.getInstance().getNum_fundible()){
            new RateNor_fundiblemalDialo_fundibleg((AppCompatActivity) requireActivity()).show();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"END","");
    }

}